<style lang="scss" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 50%;
}

</style>

<template>
  <div style="height: 100%;width: 100%;display: flex;">
    <el-card style="width: 45%; margin: 20px auto">
      <div style="text-align: right; margin-bottom: 20px;display: flex;justify-content: right">
        <div @click="data.updatePassword = true;data.updatePasswordInfo = {}"
             style="cursor: pointer;color: #72767b;width: 15%;">
          修改密码
        </div>
      </div>
      <el-form @keyup.enter="save" :model="data.form" label-width="100px"
               style="padding:0 30px 0 0;box-sizing: border-box">
        <div style="margin: 15px 0 15px 15px; text-align: center">
          <el-upload
              class="avatar-uploader"
              :action=" API_BASE_URL + '/avatar/upload'"
              :show-file-list="false"
              :on-success="updateAvatar"
          >
            <el-avatar :size="100" :src="data.form.avatar" alt="点击上传头像"/>
          </el-upload>
        </div>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" placeholder="请输入用户名" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="data.form.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="data.form.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>

        <div style="margin: 40px 0 10px 0;display: flex;justify-content: space-evenly">
          <router-link to="/index">
            <el-button type="primary">首页</el-button>
          </router-link>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card v-if="data.updatePassword" style="width: 30%;height: 40%; margin: 20px auto">
      <el-form :model="data.updatePasswordInfo" label-width="100px">
        <el-form-item label="原密码">
          <el-input v-model="data.updatePasswordInfo.oldPassword" style="width: 80%;" placeholder="请输入原密码"/>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="data.updatePasswordInfo.newPassword" style="width: 80%;" placeholder="请输入新密码"/>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="data.updatePasswordInfo.confirmPassword" style="width: 80%;" placeholder="请确认新密码"/>
        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: space-around">
        <el-button @click="data.updatePassword = false">取消</el-button>
        <el-button @click="updatePassword">确认</el-button>
      </div>

    </el-card>
  </div>
</template>

<script setup>

import {API_BASE_URL} from '@/config';
import {onMounted, reactive} from "vue";
//初始化表格
import {ElMessage} from 'element-plus';
import request from "@/utils/request.js";
import {useRouter} from "vue-router";

const router = useRouter();

const dataString = localStorage.getItem('data');
const LoginData = dataString ? JSON.parse(dataString) : null;

console.log(LoginData)

//相当于data(){}
const data = reactive({
  //弹窗默认关闭
  updatePassword: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //编辑表单
  form: {},
  updatePasswordInfo: {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  },
  originalAvatar:'',
  originalNickName:'',
});

// 然后在 onMounted 钩子中调用 Load 方法获取数据
onMounted(() => {
  Load();
});

const Load = () => {
  if (LoginData) {
    request.get(`/user/getUserRolesDetailByUsername?username=${LoginData.username}`).then((res) => {
      console.log("获取数据：", res);
      data.form = res
      data.originalAvatar = res.avatar;
      data.originalNickName = res.nickname;
    });
  }
};

const updateAvatar = (res) => {
  console.log("更新用户头像：", res.data)
  data.form.avatar = res.data
}

const save = () => {
  request.put(`/user/setting`, data.form).then((res) => {
    console.log(res)
    if (res.code === 500) {
      ElMessage.info("该邮箱已被绑定，请更换其他邮箱")
    }else {
      if (res.data) {
        ElMessage.info("设置成功")

        //更新本地数据。减少从后端发起请求获取新数据
        if (data.form.avatar !== LoginData.avatar){
          LoginData.avatar = data.form.avatar;
        }
        if (data.form.nickname !== LoginData.nickname){
          LoginData.nickname = data.form.nickname;
        }
        if (data.form.fullName !== LoginData.fullName){
          LoginData.fullName = data.form.fullName;
        }
        if (data.form.email !== LoginData.email){
          LoginData.email = data.form.email;
        }

        localStorage.removeItem("data");
        localStorage.setItem("data", JSON.stringify(LoginData));

        Load();
        if (data.originalAvatar !== data.form.avatar  || data.originalNickName !== data.form.nickname){
          window.location.reload();//页面刷新
        }
      } else {
        ElMessage.error("设置失败")
      }
    }
  })
}

const updatePassword = () => {
  let loginPassword = localStorage.getItem("password")
  if (loginPassword) {
    if (loginPassword !== data.updatePasswordInfo.oldPassword) {
      ElMessage.error("原密码输入错误");
    } else if (data.updatePasswordInfo.newPassword !== data.updatePasswordInfo.confirmPassword) {
      ElMessage.error("密码输入不一致")
    } else {
      //发请求改密码
      request.put(`/user/updatePassword/${LoginData.userId}`, data.updatePasswordInfo.newPassword).then((res) => {
        if (res.data) {
          ElMessage.info("更改密码成功")
          data.updatePassword = false
        } else {
          ElMessage.error("更改密码失败")
        }
      })
    }
  } else {
    ElMessage.error("登录已过期，请重新登录")
    router.push("/setting")
  }
}
</script>



